package com.isoft.farm.service.Impl;

import com.isoft.farm.common.ServiceException;
import com.isoft.farm.common.annotation.RequiredCache;
import com.isoft.farm.dao.SysMenuDao;
import com.isoft.farm.dao.SysRoleMenuDao;
import com.isoft.farm.entity.Node;
import com.isoft.farm.entity.SysMenu;
import com.isoft.farm.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

@Service
public class SysMenuServiceImpl implements SysMenuService {
    @Autowired
    SysMenuDao sysMenuDao;
    @Autowired
    SysRoleMenuDao sysRoleMenuDao;
    @Override
    public List<Map<String, Object>> findObjects() {
        List<Map<String, Object>> list=sysMenuDao.findObjects();
        if (list==null||list.size()==0){
            throw new ServiceException("没有菜单信息");
        }
        return list;
    }

    @Override
    public int deleteObject(Integer id) {
        if(id==null||id<=0){
            throw new IllegalArgumentException("请先选择");
        }
        int count=sysMenuDao.getChileCount(id);
        if(count>0){
            throw new ServiceException("请先删除子菜单");
        }
        sysRoleMenuDao.deleteObjectsByMenuId(id);
        int rows=sysMenuDao.deleteObjects(id);
        if (rows==0){
            throw new ServiceException("此菜单已经不存在了");
        }
        return rows;
    }

    @Override
    public List<Node> findZtreeMenuNodes() {
        return sysMenuDao.findZtreeMenuNodes();
    }


    @Override
    @RequiredCache
    public int saveObject(SysMenu sysMenu) {
        if (sysMenu==null){
            throw new IllegalArgumentException("保存对象值不能为空");
        }
        if ((StringUtils.isEmpty(sysMenu.getName()))){
            throw new IllegalArgumentException("菜单名不能为空");
        }
        int row=sysMenuDao.insertObject(sysMenu);
        return row;
    }

    @Override
    public int updateObject(SysMenu sysMenu) {
        if(sysMenu==null){
            throw new IllegalArgumentException("修改的对象不能为空");
        }
        if(StringUtils.isEmpty(sysMenu.getName())){
            throw new IllegalArgumentException("菜单名称不能为空");
        }
        //更新数据
        int row=sysMenuDao.updateObject(sysMenu);
        if (row==0){
            throw new ServiceException("记录已经不存在");
        }
        return row;
    }
}
